
package com.hdoit.ares.web.acc.apis;

import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import io.swagger.annotations.ApiParam;

import java.lang.reflect.Field;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

import javax.annotation.Resource;

import org.springframework.stereotype.Controller;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.CrossOrigin;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;

import com.hdoit.ares.logical.acc.model.AccountInfo;
import com.hdoit.ares.logical.acc.model.GoldenBeanDetail;
import com.hdoit.ares.logical.acc.model.IncomeDetail;
import com.hdoit.ares.logical.acc.model.IncomeInfo;
import com.hdoit.ares.logical.acc.model.WithdrawParam;
import com.hdoit.ares.logical.acc.service.IAccountInfoService;
import com.hdoit.ares.logical.acc.service.IGoldenBeanDetailService;
import com.hdoit.ares.logical.acc.service.IIncomeDetailService;
import com.hdoit.ares.logical.acc.service.IIncomeInfoService;
import com.hdoit.ares.logical.acc.service.IWithdrawParamService;
import com.hdoit.ares.logical.cust.model.Customer;
import com.hdoit.ares.logical.cust.service.ICustomerService;
import com.hdoit.ares.selfcommon.utils.AddMonthUtil;
import com.tennetcn.common.logical.setting.model.ParamOption;
import com.tennetcn.common.logical.setting.service.IParamOptionService;
import com.tennetcn.common.utils.DateUtils;
import com.tennetcn.component.webapi.BaseApi;
import com.tennetcn.component.webapi.ResponseModel;
import com.tennetcn.component.webapi.ResponseStatus;

@Controller
@RequestMapping(value = "/api/v1/personCenter/",method = {RequestMethod.GET,RequestMethod.POST},produces="application/json;charset=utf-8")
@Api(value="/api/v1/personCenter/")
@CrossOrigin(origins = "*",maxAge = 3600)
public class PersonCenterApi extends BaseApi{
	
	private ICustomerService customerService;
	public ICustomerService getCustomerService() {
		return customerService;
	}
	@Resource
	public void setCustomerService(ICustomerService customerService) {
		this.customerService = customerService;
	}
	
	private IIncomeInfoService incomeInfoService;
	public IIncomeInfoService getIncomeInfoService() {
		return incomeInfoService;
	}
	@Resource
	public void setIncomeInfoService(IIncomeInfoService incomeInfoService) {
		this.incomeInfoService = incomeInfoService;
	}
	
	private IAccountInfoService accountInfoService;
	public IAccountInfoService getAccountInfoService() {
		return accountInfoService;
	}
	@Resource
	public void setAccountInfoService(IAccountInfoService accountInfoService) {
		this.accountInfoService = accountInfoService;
	}

	private IGoldenBeanDetailService goldenBeanDetailService;
	public IGoldenBeanDetailService getGoldenBeanDetailService() {
		return goldenBeanDetailService;
	}
	@Resource
	public void setGoldenBeanDetailService(IGoldenBeanDetailService goldenBeanDetailService) {
		this.goldenBeanDetailService = goldenBeanDetailService;
	}
	
	private IIncomeDetailService incomeDetailService;
	public IIncomeDetailService getIncomeDetailService() {
		return incomeDetailService;
	}
	@Resource
	public void setIncomeDetailService(IIncomeDetailService incomeDetailService) {
		this.incomeDetailService = incomeDetailService;
	}
	
	private IParamOptionService paramOptionService;
	public IParamOptionService getParamOptionService() {
		return paramOptionService;
	}
	@Resource
	public void setParamOptionService(IParamOptionService paramOptionService) {
		this.paramOptionService = paramOptionService;
	}
	
	private IWithdrawParamService withdrawParamService;
	

	public IWithdrawParamService getWithdrawParamService() {
		return withdrawParamService;
	}
	@Resource
	public void setWithdrawParamService(IWithdrawParamService withdrawParamService) {
		this.withdrawParamService = withdrawParamService;
	}

	private final String accountApi = "account";
	private final String goldBeanApi = "goldBean";
	private final String incomeApi = "income";
	private final String goldBeanToBalanceApi = "goldBeanToBalance";
	private final String incomeToBalanceApi = "incomeToBalance";
	private final String personDetailedApi = "personDetailed";
	
	@ResponseBody
	@RequestMapping(value = accountApi)
	@ApiOperation(notes= accountApi,httpMethod = "POST" ,value = "查找当前用户的账户金总金豆和总奖金")
	public String account(){
		ResponseModel rm = new ResponseModel();
		
		String customerId = getLoginId();
		Double income = incomeInfoService.queryIncomeBalance(customerId);
		Double goldBean = accountInfoService.queryGoldBean(customerId);
		Customer customer = customerService.queryModel(customerId);
		
		//判断是否为空
		if(income != null && goldBean != null && customer != null){
			rm.setStatus(ResponseStatus.success);
			
			List<String> params = new ArrayList<String>();
			params.add("id");
			params.add("username");
			params.add("nickname");
			params.add("userIdentity");
			params.add("sex");
			params.add("phone");
			params.add("refereeId");
			params.add("refereeIdentity");
			params.add("region");
			params.add("level");
			params.add("picPath");
			params.add("birthday");
			params.add("email");
			
			rm.putObj("customer", customer,params);
			rm.setMessage("ok");
			rm.put("income", income);
			rm.put("goldBean", goldBean);
		}else{
			rm.setStatus(ResponseStatus.dataError);
			rm.setMessage("未找到该用户相关信息");
		}
		return rm.toJson();
	}
	
	@ResponseBody
	@RequestMapping(value = goldBeanApi)
	@ApiOperation(notes= goldBeanApi,httpMethod = "POST" ,value = "用于查找当前用户可用金豆和不可用金豆")
	public String goldBean(){
		ResponseModel rm = new ResponseModel();
		
		String customerId = getLoginId();
		
		AccountInfo accountInfo  = accountInfoService.queryModelByCustomerId(customerId);
		if(accountInfo != null){
			ParamOption paramOption = paramOptionService.queryModelByParamName("exchange");
			int exchangeRate = Integer.valueOf(paramOption.getParamValue());
			
			Double allGoldBean = accountInfo.getGoldenBean();

			// 得到犹豫期余额
			Double uselessGoldBean = 0.0;
			GoldenBeanDetail goldenBeanDetail = goldenBeanDetailService.queryGoldenInHesitate(customerId);
			if (goldenBeanDetail == null) {
				uselessGoldBean = 0.0;
			} else {
				uselessGoldBean = goldenBeanDetail.getSumgolden();
			}
			Double useGoldBean = allGoldBean - uselessGoldBean;
			
			rm.setStatus(ResponseStatus.success);
			rm.setMessage("ok");
			rm.put("useGoldenBean", useGoldBean);
			rm.put("uselessGoldenBean", uselessGoldBean);
			rm.put("exchangeRate", exchangeRate);
		}else{
			rm.setStatus(ResponseStatus.dataError);
			rm.setMessage("未找到该用户相关账户");
		}
		
		
		return rm.toJson();
		
	}
	
	@ResponseBody
	@RequestMapping(value = incomeApi)
	@ApiOperation(notes = incomeApi, httpMethod = "POST", value = "用于查找当前用户可用奖金和不可用奖金")
	public String income() {

		ResponseModel rm = new ResponseModel();
		String customerId = getLoginId();

		IncomeInfo incomeInfo = incomeInfoService.queryIncomeInfo(customerId);
		if (incomeInfo != null) {
			Double allIncome = incomeInfo.getIncomeBalance();

			// 得到犹豫期余额
			Double uselessIncome = 0.0;
			IncomeDetail incomeDetail = incomeDetailService.queryIncomeInHesitate(customerId);
			if (incomeDetail == null) {
				uselessIncome = 0.0;
			} else {
				uselessIncome = incomeDetail.getSumincome();
			}
			Double useIncome = allIncome - uselessIncome;
			
			rm.setStatus(ResponseStatus.success);
			rm.setMessage("ok");
			rm.put("useIncome", useIncome);
			rm.put("uselessIncome", uselessIncome);
		}else{
			rm.setStatus(ResponseStatus.dataError);
			rm.setMessage("未找到该用户的奖金账户");
		}

		return rm.toJson();

	}
	
	@ResponseBody
	@RequestMapping(value = incomeToBalanceApi)
	@ApiOperation(notes= incomeToBalanceApi,httpMethod = "POST" ,value = "用于将奖金转入余额")
	public String incomeToBalance(@ApiParam("转入到余额的奖金(必填)") @RequestParam(value="money",required=true)String money){
		
		ResponseModel rm = new ResponseModel();
		String customerId = getLoginId();
		
		double useIncome =(double)getIncome(customerId).get("useIncome");
		double changeIncome = Double.valueOf(money);
		if(changeIncome>0&&changeIncome<=useIncome){
			
			Customer customer = customerService.queryModel(customerId);

			Boolean res = accountInfoService.updateIncomeToBalance(customer,changeIncome);

			if (res) {
				rm.setStatus(ResponseStatus.success);
				rm.setMessage("ok");
			} else {
				rm.setStatus(ResponseStatus.dataError);
				rm.setMessage("奖金转入余额时发生错误");
			}
		}else {
			rm.setStatus(ResponseStatus.dataError);
			rm.setMessage("转入的奖金大于可转入的奖金");
		}
		
		
		return rm.toJson();
		
	}
	
	
	@ResponseBody
	@RequestMapping(value = goldBeanToBalanceApi)
	@ApiOperation(notes= goldBeanToBalanceApi,httpMethod = "POST" ,value = "用于将金豆转入余额")
	public String goldBeanToBalance(@ApiParam("转入到余额的金豆(必填)") @RequestParam(value="goldBean",required=true)String goldBean){
		
		ResponseModel rm = new ResponseModel();
		String customerId = getLoginId();
		double useGoldBean =  (double) getGoldBean(customerId).get("useGoldBean");
		double change = Double.valueOf(goldBean);
		if(change>0&&change<=useGoldBean){
			
			Customer customer = customerService.queryModel(customerId);
			Boolean res = accountInfoService.updateGoldToBalance(customer,change);
			if (res) {
				rm.setStatus(ResponseStatus.success);
				rm.setMessage("ok");
			} else {
				rm.setStatus(ResponseStatus.dataError);
				rm.setMessage("金豆转入余额遇到错误");
			}
		}else {
			rm.setStatus(ResponseStatus.dataError);
			rm.setMessage("转入金豆大于可转入的金豆");
		}		
		return rm.toJson();
		
	}
	
	
	
	//用于提取查询可用金豆和不可用金豆的公共方法
	public HashMap<String,Object> getGoldBean(String id){
		HashMap<String,Object> map = new HashMap<String,Object>();
		
		AccountInfo accountInfo  = accountInfoService.queryModelByCustomerId(id);
		
		Double allGoldBean = accountInfo.getGoldenBean();

		// 得到犹豫期余额
		Double uselessGoldBean = 0.0;
		GoldenBeanDetail goldenBeanDetail = goldenBeanDetailService.queryGoldenInHesitate(id);
		if (goldenBeanDetail == null) {
			uselessGoldBean = 0.0;
		} else {
			uselessGoldBean = goldenBeanDetail.getSumgolden();
		}
		Double useGoldBean = allGoldBean - uselessGoldBean;
		map.put("uselessGoldBean", uselessGoldBean);
		map.put("useGoldBean", useGoldBean);
		
		return map;
	}
	
	
	//用于提取查询可用奖金和不可用奖金的公共方法
	public HashMap<String,Object> getIncome(String id){

		IncomeInfo incomeInfo = new IncomeInfo();
		incomeInfo = incomeInfoService.queryIncomeInfo(id);

		Double allIncome = incomeInfo.getIncomeBalance();

		// 得到犹豫期余额
		Double uselessIncome = 0.0;
		IncomeDetail incomeDetail = incomeDetailService.queryIncomeInHesitate(id);
		if (incomeDetail == null) {
			uselessIncome = 0.0;
		} else {
			uselessIncome = incomeDetail.getSumincome();
		}
		Double useIncome = allIncome - uselessIncome;
		
		HashMap<String, Object> res = new HashMap<String, Object>();
		res.put("useIncome", useIncome);
		res.put("uselessIncome", uselessIncome);
		return res;
	}

	@ResponseBody
	@RequestMapping(value = personDetailedApi)
	@ApiOperation(notes= personDetailedApi,httpMethod = "POST" ,value = "个人资料及修改")
	public String personDetailed(@ApiParam("昵称") @RequestParam(value="nickname",required=false)String nickname,
								 @ApiParam("生日") @RequestParam(value="birthday",required=false)String birthday,
								 @ApiParam("地区") @RequestParam(value="region",required=false)String region,
								 @ApiParam("邮箱") @RequestParam(value="email",required=false)String email ){
				
		ResponseModel rm = new ResponseModel();

		Customer changecustomer = new Customer();
				
		changecustomer.setId(getLoginId());
		if (!StringUtils.isEmpty(nickname)) {
			changecustomer.setNickname(nickname);
		}
		if (!StringUtils.isEmpty(region)) {
			changecustomer.setRegion(region);
		}
		if (!StringUtils.isEmpty(email)) {
			changecustomer.setEmail(email);
		}
		if (birthday!=null) {
			
			if(isDate(birthday)){
				System.err.println("日期格式正常");
				Date date_birthday = new Date();
				try {
					date_birthday = new SimpleDateFormat("yyyy-MM-dd").parse(birthday);
				} catch (ParseException e) {
					rm.setMessage("日期格式错误 yyyy-MM-dd");
					return rm.toJson();
				}
				 
				changecustomer.setBirthday(date_birthday);
			}else {
				System.err.println("日期错误");
				rm.setStatus(ResponseStatus.dataError);
				rm.setMessage("日期格式错误 yyyy-MM-dd");
				return rm.toJson();
			}
			
		}
		
		if(customerService.updateCustDetail(changecustomer)){
			rm.setMessage("修改个人信息成功");
		}
		
		Customer customer=customerService.queryModel(getLoginId()); 
				
		String isMaker = "noMaker";
		
		if(customer.getLevel().equals("vip")||customer.getLevel().equals("visitor")){
			isMaker = "notMaker";
		}else {	
			if(customer.getUpdateRegionDate()==null){
				customer.setUpdateRegionDate(DateUtils.getCurrent());
			}
			WithdrawParam withdrawParam1 =withdrawParamService.queryModelByHelpCode("regionIntervalTime");
			WithdrawParam withdrawParam2 =withdrawParamService.queryModelByHelpCode("regionUpdateTime");
			int month = withdrawParam1.getParam();
			int day = withdrawParam2.getParam();
			Date nowDate = DateUtils.getCurrent();
			Date changeDate =AddMonthUtil.addMonth(month, customer.getUpdateRegionDate());
			Date overDate = DateUtils.addDay(day, changeDate);	
				
				
			if (DateUtils.compare_date(nowDate, changeDate)==1 && DateUtils.compare_date(nowDate, overDate)==-1) {				
				isMaker = "yesMaker";				
			}else {
				isMaker = "noMaker";
			}
			rm.put("month", month);
		}
				
		List<String> params = new ArrayList<String>();
		params.add("id");
		params.add("username");
		params.add("nickname");
		params.add("userIdentity");
		params.add("sex");
		params.add("phone");
		params.add("refereeId");
		params.add("refereeIdentity");
		params.add("region");
		params.add("level");
		params.add("picPath");
		params.add("birthday");
		params.add("email");

		rm.putObj("customer", customer,params);
		rm.put("isMaker",isMaker);

		return rm.toJson();
	}
	
	
	public boolean isDate(String date)  
    {  
        /** 
         * 判断日期格式和范围 
         */  
        String rexp = "^(([0-9]{3}[1-9]|[0-9]{2}[1-9][0-9]{1}|[0-9]{1}[1-9][0-9]{2}|[1-9][0-9]{3})-(((0[13578]|1[02])-(0[1-9]|[12][0-9]|3[01]))|((0[469]|11)-(0[1-9]|[12][0-9]|30))|(02-(0[1-9]|[1][0-9]|2[0-8]))))|((([0-9]{2})(0[48]|[2468][048]|[13579][26])|((0[48]|[2468][048]|[13579][26])00))-02-29)";  
          
        Pattern pat = Pattern.compile(rexp);    
          
        Matcher mat = pat.matcher(date);    
          
        boolean dateType = mat.matches();  

        return dateType;  
    }  
}
